package com.github.limit.interceptor;

import com.github.limit.context.LimitContext;
import com.github.limit.response.IResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author: wangdejun
 * @create: 2019-10-11 16:43
 **/
@Slf4j
public class AccessInterceptor implements HandlerInterceptor {


    @Autowired
    private LimitContext limitContext;

    @Autowired
    private IResult iResult;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 之拦截HandlerMethod
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        Method method = handlerMethod.getMethod();
        boolean flag = limitContext.start(method);
        if (flag == false) {
            iResult.send(request, response);
        }
        return flag;
    }

}
